package com.neusoft.EYSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.EYSystem.dao.BedDAO;
import com.neusoft.EYSystem.dao.BedUsageDAO;
import com.neusoft.EYSystem.dao.CheckoutApplyDAO;
import com.neusoft.EYSystem.dao.ClientDAO;
import com.neusoft.EYSystem.po.*;
import com.neusoft.EYSystem.service.CheckoutApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CheckoutApplyServiceImpl implements CheckoutApplyService {
    @Autowired
    private CheckoutApplyDAO checkoutApplyDAO;

    @Autowired
    private ClientDAO clientDAO;

    @Autowired
    private BedDAO bedDAO;

    @Autowired
    private BedUsageDAO bedUsageDAO;

    @Override
    public PageResponseBean<List<ClientCheckoutApply>> checkoutPage(String name, String checkoutDateStart, String checkoutDateEnd, String approvalStatus, String userId, Long page, Long size) {
        // 找到所有满足要求的Clientid
        QueryWrapper<Client> clientQueryWrapper = new QueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            clientQueryWrapper.like("name", name);
        }else{
            clientQueryWrapper.isNotNull("name"); // 如果没有提供名字，则查询所有客户
        }

        List<Integer> clientIds = clientDAO.selectList(clientQueryWrapper)
                .stream()
                .map(Client::getClientId)
                .toList();

        if (clientIds.isEmpty()) {
            return new PageResponseBean<>(200, "没有找到符合条件的客户");
        }

        // 查询退住申请
        QueryWrapper<CheckoutApply> checkoutApplyQueryWrapper = new QueryWrapper<>();
        checkoutApplyQueryWrapper.in("client_id", clientIds);
        checkoutApplyQueryWrapper.eq("is_visible", true); // 只查询可见的退住申请
        if( approvalStatus != null && !approvalStatus.isEmpty()) {
            checkoutApplyQueryWrapper.eq("approval_status", approvalStatus);
        }

        if (userId != null){
            checkoutApplyQueryWrapper.eq("user_id", userId); // 根据userId查询
        }

        // 时间处理
        if (checkoutDateStart != null && !checkoutDateStart.isEmpty() && checkoutDateEnd != null && !checkoutDateEnd.isEmpty()) {
            checkoutApplyQueryWrapper.between("discharge_time", checkoutDateStart, checkoutDateEnd);
        } else if (checkoutDateStart != null && !checkoutDateStart.isEmpty()) {
            checkoutApplyQueryWrapper.ge("discharge_time", checkoutDateStart);
        } else if (checkoutDateEnd != null && !checkoutDateEnd.isEmpty()) {
            checkoutApplyQueryWrapper.le("discharge_time", checkoutDateEnd);
        }

        checkoutApplyQueryWrapper.orderBy(true, false, "discharge_time"); // 按退住时间降序排列

        // 分页查询开始
        IPage<CheckoutApply> checkoutApplyPage = new Page<>(page, size);
        IPage<CheckoutApply> checkoutApplies = checkoutApplyDAO.selectPage(checkoutApplyPage, checkoutApplyQueryWrapper);

        // 先查出所有涉及到的Client

        Set<Integer> resultClientIds = checkoutApplies.getRecords()
                .stream()
                .map(CheckoutApply::getClientId)
                .collect(Collectors.toSet());
        Map<Integer, Client> clientMap = new HashMap<>();

        if(!resultClientIds.isEmpty()) {
            QueryWrapper<Client> clientQuery = new QueryWrapper<>();
            clientQuery.in("client_id", resultClientIds);
            clientMap = clientDAO.selectList(clientQuery).stream()
                    .collect(Collectors
                            .toMap(Client::getClientId, client -> client));
        }else{
            return new PageResponseBean<>(500, "没有找到符合条件的客户");
        }

        // 组装结果
        List<ClientCheckoutApply> result = new ArrayList<>();
        for( CheckoutApply checkoutApply : checkoutApplies.getRecords()) {
            ClientCheckoutApply clientCheckoutApply = new ClientCheckoutApply();
            clientCheckoutApply.setClient(clientMap.get(checkoutApply.getClientId()));
            clientCheckoutApply.setCheckoutApply(checkoutApply);
            result.add(clientCheckoutApply);
        }

        // 封装结果对象

        PageResponseBean<List<ClientCheckoutApply>> responseBean = new PageResponseBean<>();
        responseBean.setData(result);
        responseBean.setTotal(checkoutApplies.getTotal());
        responseBean.setStatus(200);
        responseBean.setMsg("查询成功");

        return responseBean;
    }

    @Transactional
    @Override
    public ResponseBean<Integer> approvalCheckoutApply(CheckoutApply checkoutApply) {
        // 1. 更新申请状态
        int updateCount = checkoutApplyDAO.updateById(checkoutApply);
        if (updateCount > 0) {
            // 2. 如果申请通过，更新客户状态
            if(("正常退住".equals(checkoutApply.getDischargeType()) || "死亡退住".equals(checkoutApply.getDischargeType())) && "通过".equals(checkoutApply.getApprovalStatus())) {
                Client client = clientDAO.selectById(checkoutApply.getClientId());
                if (client != null) {
                    client.setStatus("deactive");
                    int clientUpdateCount = clientDAO.updateById(client);
                    if (clientUpdateCount <= 0) {
                        return new ResponseBean<>(500, "更新客户状态失败");
                    }else {
                        Bed bed = bedDAO.selectById(client.getBedId());
                        if (bed != null) {
                            bed.setStatus("free");
                            int bedUpdateCount = bedDAO.updateById(bed);
                            if (bedUpdateCount <= 0) {
                                return new ResponseBean<>(500, "更新床位状态失败");
                            }else{
                                // 3. 更新床位使用记录
                                BedUsage bedUsage = new BedUsage();
                                QueryWrapper<BedUsage> bedUsageQueryWrapper = new QueryWrapper<>();
                                bedUsageQueryWrapper.eq("client_id", client.getClientId())
                                        .eq("bed_id", bed.getBedId());
                                List<BedUsage> bus = bedUsageDAO.selectList(bedUsageQueryWrapper);
                                for( BedUsage bu : bus) {
                                    if("使用中".equals(bu.getStatus())) {
                                        bedUsage.setUsageId(bu.getUsageId());
                                        break;
                                    }
                                }
                                bedUsage.setEndDate(checkoutApply.getApprovalTime());
                                bedUsage.setStatus("已结束");
                                int bedUsageUpdateCount = bedUsageDAO.updateById(bedUsage);
                                if (bedUsageUpdateCount <= 0) {
                                    return new ResponseBean<>(500, "更新床位使用记录失败");
                                }
                            }
                        } else {
                            return new ResponseBean<>(404, "床位不存在");
                        }
                    }
                } else {
                    return new ResponseBean<>(404, "客户不存在");
                }
            }
            return new ResponseBean<>(200, "更新退住记录申请成功", updateCount);
        } else {
            return new ResponseBean<Integer>(500, "更新退住记录申请失败");
        }
    }

    @Override
    public ResponseBean<Integer> deleteLogic(Integer applyId) {
        CheckoutApply checkoutApply = checkoutApplyDAO.selectById(applyId);
        if (checkoutApply != null) {
            checkoutApply.setVisible(false);
            int updateCount = checkoutApplyDAO.updateById(checkoutApply);
            if (updateCount > 0) {
                return new ResponseBean<Integer>(200, "删除退住记录申请成功",updateCount);
            } else {
                return new ResponseBean<Integer>(500, "删除退住记录申请失败");
            }
        }
        return new ResponseBean<Integer>(404, "退住记录申请不存在");
    }
}
